package com.raymond.mybatisspring.util;

import java.lang.annotation.Annotation;
import java.util.Map;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author raymond 2013-11-17 下午3:22:28
 *
 */
public class SpringUtil {
	private static ApplicationContext CONTEXT;
	
	public static ApplicationContext getBeanFactory() {
		if(CONTEXT == null) {
			synchronized(ApplicationContext.class) {
				if(CONTEXT == null) {
					CONTEXT = newClassPathXmlApplicationContext("applicationContext-basic.xml");
				}
			}
		}
		return CONTEXT;
	}
	
	public static ApplicationContext newApplicationContext(String config) {
		return newClassPathXmlApplicationContext(config);
	}
	
	private static ClassPathXmlApplicationContext newClassPathXmlApplicationContext(String config) {
		return new ClassPathXmlApplicationContext(config);
	}
	
	public static Object getBean(String name) {
		return getBeanFactory().getBean(name);
	}
	
	public static <T> T getBean(String name, Class<T> clazz) {
		return getBeanFactory().getBean(name, clazz);
	}
	
	public static String[] getBeanNames() {
		return getBeanFactory().getBeanDefinitionNames();
	}
	
	public static void publishEvent(ApplicationEvent event) {
		getBeanFactory().publishEvent(event);
	}
	
	public static Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotation) {
		return getBeanFactory().getBeansWithAnnotation(annotation);
	}
	
	public static <T> Map<String, T> getBeansOfType(Class<T> type) {
		return getBeanFactory().getBeansOfType(type);
	}
	
}
